package cesaredu.midchat.phoneinformation;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.TelephonyManager;

public class PhoneInformation {
	
	private String localPhoneNumber;
	private Map<String, Contact> contacts;
	
	public String getLocalPhoneNumber() {
		return this.localPhoneNumber;
	}

	public Map<String, Contact> getContacts() {
		return this.contacts;
	}

	public PhoneInformation(Context context) {
		this.localPhoneNumber = this.getLocalPhoneNumber(context);
		this.contacts = this.getContacts(context);
	}
	
	private String getLocalPhoneNumber(Context context) {
		TelephonyManager tMgr = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
		return tMgr.getLine1Number();
	}
	
	private Map<String, Contact> getContacts(Context context) {
		Map<String, Contact> contacts = new HashMap<String, Contact>();
		
		ContentResolver cr = context.getContentResolver();
	    Cursor curContacts = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

	    try {
	    	while (curContacts.moveToNext()) {
		        String id = curContacts.getString(curContacts.getColumnIndex(ContactsContract.Contacts._ID));
		        String name = curContacts.getString(curContacts.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
		        List<String> phoneNumbers = new LinkedList<String>();
		        
		        Cursor curPhones = cr.query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + " = " + id, null, null);
		        
		        try {
		        	while (curPhones.moveToNext()) {
		        		String phoneNumber = curPhones.getString(curPhones.getColumnIndex(Phone.NUMBER));
		        		
		        		phoneNumbers.add(phoneNumber);
			        }
		        } finally {
		        	curPhones.close();
		        }

		        Contact contact = new Contact();
		        contact.setId(id);
		        contact.setName(name);
		        contact.setPhoneNumbers(phoneNumbers.toArray(new String[0]));
		        
		        contacts.put(contact.getId(), contact);
		    }
	    } finally {
	    	curContacts.close();
	    }
	    
	    return contacts;
	}
}